<?php
namespace app\admin\model;
use think\Model;
class Cate extends Model
{
    //栏目树
    public function catetree(){
        $cates = $this->order('sort desc')->select();
        return $this->sort($cates);
        //对栏目进行分类，排序
    }

    //无限级分类排序
    public function sort($data,$pid = 0,$level = 0){
        //pid 上级默认为0，level 一级为0 二级为1 三级为2
        static $arr = array();
        foreach ($data as $k => $v) {
            if($v['pid'] == $pid){
                // 1.pid=0，
                $v['level'] = $level;
                // 2.level=0，
                $arr[] = $v;
                // 3.$v复制给空数组
                $this->sort($data,$v['id'],$level + 1);
            }
        }
        return $arr;
    }

    //获取子元素id
    public function getchildrenid($cateid){
        $cates = $this->select();
        return $this->_getchildrenid($cates,$cateid);
    }

    public function _getchildrenid($cates,$cateid){
        static $arr = array();
        foreach ($cates as $k => $v) {
            if($v['pid'] == $cateid){
                $arr[] = $v['id'];
                $this->_getchildrenid($cates,$v['id']);
            }
        }
        return $arr;
    }
    
    protected static function init()
    {
        //新增前
        Cate::event('before_insert',function ($data){
            if ($_FILES['thumb']['tmp_name']){
                $file = request()->file('thumb');
                $info = $file->move(ROOT_PATH . 'public' . DS .'static/uploads');
                if ($info){
//                    $thumb=ROOT_PATH . 'public' . DS .'uploads'.'/'.$info->getSaveName();
                    $thumb = '/static/uploads'.'/'.$info->getSaveName();
                    $data['thumb'] = $thumb;
                }
            }
        });
        //更新前
        Cate::event('before_update',function ($data){
            if ($_FILES['thumb']['tmp_name']){
                $cate = Cate::find($data->id);
//                echo $_SERVER['DOCUMENT_ROOT'];die;
                $thumbpath = $_SERVER['DOCUMENT_ROOT'].$cate['thumb'];
                if (file_exists($thumbpath)){
                    @unlink($thumbpath);
                }
                $file = request()->file('thumb');
                $info = $file->move(ROOT_PATH . 'public' . DS .'static/uploads');
                if ($info){
                    $thumb = '/static/uploads'.'/'.$info->getSaveName();
                    $data['thumb'] = $thumb;
                }
            }
        });
        //删除前
        Cate::event('before_delete',function ($data){
            $cate = Cate::find($data->id);
            $thumbpath = $_SERVER['DOCUMENT_ROOT'].$cate['thumb'];
            if (file_exists($thumbpath)){
                @unlink($thumbpath);
            }
        });
    }
}

